<script setup>
import { ref, onMounted } from "vue"
import homeApi from "@/api/homeApi";
import popApi from "@/api/popApi";
import goodApi from "@/api/goodApi";
import Upload from "@/components/Upload.vue";
import { Message } from "@arco-design/web-vue";
import { IconEdit, IconDelete } from "@arco-design/web-vue/es/icon";

const advertList = ref([]);
const popConfigs = ref([]);
const productList = ref([]);
const productLoading = ref(false);

const screenPopConfig = ref({ url: "", type: 1 });
const topPopConfig = ref({ url: "", type: 2 });// 首页顶部动态图
const homePopConfig = ref({ url: "", type: 3 });
const productPopConfigs = ref([]);

// 定义轮播图编辑弹窗的可见性和表单数据
const advertVisible = ref(false);
const productVisible = ref(false);
const currentAdvert = ref({
    id: '',
    adName: '',
    adImgUrl: '',
    adLink: '',
    adSort: 0
});
const productAdvert = ref({
    id: '',
    skipGoodId: '',
    url: '',
    sortId: 0,
    type:4
});
const isEditMode = ref(false);
// 商品查询参数
const productSearchParams = ref({
    goodsName: '',
});

const getAllAdvertList = () => {
    homeApi.getAdvertList().then(res => {
        advertList.value = res;
    })
}

const getAllPop = () => {
    popApi.list().then(res => {
        popConfigs.value = res;
        res.forEach(item => {
            if (item.type == 1) {
                screenPopConfig.value = item;
            }
            if (item.type == 2) {
                topPopConfig.value = item;
            }
            productPopConfigs.value = res.filter(item => item.type == 4).sort((a, b) => a.sortId - b.sortId);
        });
    })
}

// 加载商品列表数据
const loadProducts = () => {
    productLoading.value = true;
    const params = {
        pageNo: 1,
        pageSize: 500, // 获取较多商品以供选择
        queryParam: productSearchParams.value
    };

    goodApi.queryPage(params).then(res => {
        productList.value = res.records;
        productLoading.value = false;
    }).catch(() => {
        productLoading.value = false;
    });
}

// 搜索商品
const searchProducts = () => {
    loadProducts();
}

// 当弹窗打开时加载商品数据
const onDialogOpen = () => {
    if (productList.value.length === 0) {
        loadProducts();
    }
}

const savePop = (type) => {
    if (type == 1) {
        popApi.save(screenPopConfig.value).then(res => {
            Message.success("保存成功")
            getAllPop()
        })
    } else if (type == 2) {
        popApi.save(topPopConfig.value).then(res => {
            Message.success("保存成功")
            getAllPop()
        })
    } else if (type == 3) {
        popApi.save(homePopConfig.value).then(res => {
            Message.success("保存成功")
            getAllPop()
        })
    }
}

// 打开编辑轮播图弹窗
const openEditAdvert = (advert) => {
    isEditMode.value = true;
    currentAdvert.value = { ...advert };
    advertVisible.value = true;
}

// 打开新增轮播图弹窗
const openAddAdvert = () => {
    isEditMode.value = false;
    currentAdvert.value = {
        id: '',
        adName: '',
        adImgUrl: '',
        adLink: '',
        adSort: advertList.value.length > 0 ? Math.max(...advertList.value.map(ad => ad.adSort)) + 1 : 1
    };
    advertVisible.value = true;
}

// 保存轮播图设置
const saveAdvert = () => {
    if (!currentAdvert.value.adImgUrl) {
        Message.error("请上传轮播图片");
        return;
    }
    homeApi.saveAdvert(currentAdvert.value).then(res => {
        Message.success("保存成功");
        advertVisible.value = false;
        getAllAdvertList();
    }).catch(err => {
        Message.error("保存失败，请重试");
    });
}

// 删除轮播图
const deleteAdvert = (advert) => {
    homeApi.deleteAdvert({ id: advert.id }).then(res => {
        Message.success("删除成功");
        getAllAdvertList();
    }).catch(err => {
        Message.error("删除失败，请重试");
    });
}

// 打开新增产品页轮播图弹窗
const openAddProduct = () => {
    isEditMode.value = false;
    productAdvert.value = {
        id: '',
        skipGoodId: '',
        url: '',
        type: 4,
        sortId: productPopConfigs.value.length > 0 ? Math.max(...productPopConfigs.value.map(ad => ad.sortId)) + 1 : 1
    };
    productVisible.value = true;
}

// 打开编辑产品页轮播图弹窗
const openEditProduct = (advert) => {
    isEditMode.value = true;
    productAdvert.value = { ...advert };
    productVisible.value = true;
}

// 保存产品页轮播图设置
const saveProduct = () => {
    if (!productAdvert.value.url) {
        Message.error("请上传轮播图");
        return;
    }
    productAdvert.value.type = 4;
    popApi.save(productAdvert.value).then(res => {
        Message.success("保存成功");
        productVisible.value = false;
        getAllPop();
    }).catch(err => {
        Message.error("保存失败，请重试");
    });
}

// 删除产品页轮播图
const deleteProduct = (advert) => {
    popApi.delete({ id: advert.id }).then(res => {
        Message.success("删除成功");
        getAllPop();
    }).catch(err => {
        Message.error("删除失败，请重试");
    });
}

onMounted(() => {
    getAllAdvertList();
    getAllPop();
    loadProducts();
})
</script>
<template>
    <div class="main-con">
        <a-row :gutter="10">
            <a-col :span="8">
                <a-card title="开屏图设置">
                    <template #extra>
                        <a-space>
                            <a-button type="primary" @click="savePop(1)">保存</a-button>
                        </a-space>
                    </template>
                    <Upload tip="上传开屏图" :height="1334 / 4" :width="750 / 4" v-model="screenPopConfig.url"></Upload>
                </a-card>
            </a-col>
            <a-col :span="8">
                <a-card title="首页顶部视频设置">
                    <template #extra>
                        <a-space>
                            <a-button type="primary" @click="savePop(2)">保存</a-button>
                        </a-space>
                    </template>
                    <Upload tip="上传首页动图" :height="1334 / 4" :width="750 / 4" v-model="topPopConfig.url"></Upload>
                </a-card>
            </a-col>
            <!-- <a-col :span="8">
                <a-card title="首页弹窗图设置">
                    <template #extra>
                        <a-space>
                            <a-button type="primary" @click="savePop(3)">保存</a-button>
                        </a-space>
                    </template>
                    <Upload tip="上传首页弹窗图" :height="1334 / 4" :width="750 / 4" v-model="homePopConfig.url"></Upload>
                </a-card>
            </a-col> -->
        </a-row>
        <a-card title="首页轮播图设置" style="margin-top: 16px;">
            <template #extra>
                <a-space>
                    <a-button type="primary" @click="openAddAdvert">添加首页轮播图</a-button>
                </a-space>
            </template>
            <div style="background-color: #f0f0f0;padding: 16px;">
                <a-row :gutter="10" :style="{ marginBottom: '10px' }">
                    <a-col v-for="ad in advertList" :key="ad.id" :xs="12" :sm="8" :md="6" :lg="6" :xl="6" :xxl="4"
                        style="margin-bottom: 20px;">
                        <a-card :title="ad.adName" :bordered="false" :style="{ width: '100%' }">
                            <template #cover>
                                <div :style="{
                                    height: '100%',
                                    overflow: 'hidden',
                                    textAlign: 'center'
                                }">
                                    <div style="padding: 10px;">
                                        <a-image width="200px" fit="scale-down" alt="dessert"
                                            :src="'http://image.fuyj.com.cn/' + ad.adImgUrl + '?imageslim'" />
                                    </div>
                                </div>
                            </template>
                            <template #extra>
                                <div class="advert-sort">排序: {{ ad.adSort }}</div>
                            </template>
                            <template #actions>
                                <a-space>
                                    <a-button type="text" @click="openEditAdvert(ad)">
                                        <template #icon><icon-edit /></template>
                                        编辑
                                    </a-button>
                                    <a-button type="text" status="danger" @click="deleteAdvert(ad)">
                                        <template #icon><icon-delete /></template>
                                        删除
                                    </a-button>
                                </a-space>
                            </template>
                        </a-card>
                    </a-col>
                </a-row>
            </div>
        </a-card>

        <a-card title="产品页轮播图设置" style="margin-top: 16px;">
            <template #extra>
                <a-space>
                    <a-button type="primary" @click="openAddProduct">添加产品页轮播图</a-button>
                </a-space>
            </template>
            <div style="background-color: #f0f0f0;padding: 16px;">
                <a-row :gutter="10" :style="{ marginBottom: '10px' }">
                    <a-col v-for="ad in productPopConfigs" :key="ad.id" :xs="12" :sm="8" :md="6" :lg="6" :xl="6"
                        :xxl="4" style="margin-bottom: 20px;">
                        <a-card :bordered="false" :style="{ width: '100%' }">
                            <template #cover>
                                <div :style="{
                                    height: '100%',
                                    overflow: 'hidden',
                                    textAlign: 'center'
                                }">
                                    <div style="padding: 10px;">
                                        <a-image width="100%" fit="scale-down" alt="dessert"
                                            :src="'http://image.fuyj.com.cn/' + ad.url + '?imageslim'" />
                                    </div>
                                </div>
                            </template>
                            <template #extra>
                                <div class="advert-sort">排序: {{ ad.sortId }}</div>
                            </template>
                            <template #actions>
                                <a-space>
                                    <a-button type="text" @click="openEditProduct(ad)">
                                        <template #icon><icon-edit /></template>
                                        编辑
                                    </a-button>
                                    <a-button type="text" status="danger" @click="deleteProduct(ad)">
                                        <template #icon><icon-delete /></template>
                                        删除
                                    </a-button>
                                </a-space>
                            </template>
                        </a-card>
                    </a-col>
                </a-row>
            </div>
        </a-card>

        <!-- 编辑轮播图弹窗 -->
        <a-modal v-model:visible="advertVisible" :title="isEditMode ? '编辑轮播图' : '添加轮播图'" @cancel="advertVisible = false"
            @ok="saveAdvert">
            <a-form :model="currentAdvert" auto-label-width>
                <a-form-item field="adImgUrl" label="轮播图图片">
                    <Upload tip="上传轮播图" :width="300" :height="450" v-model="currentAdvert.adImgUrl"></Upload>
                </a-form-item>
                <a-form-item field="adLink" label="关联商品">
                    <a-select v-model="currentAdvert.adLink" allow-search allow-clear placeholder="请选择关联商品">
                        <a-option v-for="product in productList" :key="product.goodsId"
                            :value="product.goodsId.toString()" :label="product.goodsName">
                            <div style="display: flex; align-items: center;">
                                <a-avatar size="small" style="margin-right: 8px;"
                                    :image-url="'http://image.fuyj.com.cn/' + product.goodsThumb + '?imageslim/zlevel/7'" />
                                <span>{{ product.goodsName }}</span>
                            </div>
                        </a-option>
                    </a-select>
                </a-form-item>
                <a-form-item field="adSort" label="排序">
                    <a-input-number v-model="currentAdvert.adSort" placeholder="请输入排序值" :min="1" />
                </a-form-item>
            </a-form>
        </a-modal>

        <a-modal v-model:visible="productVisible" :title="isEditMode ? '编辑轮播图' : '添加轮播图'"
            @cancel="productVisible = false" @ok="saveProduct">
            <a-form :model="productAdvert" auto-label-width>
                <a-form-item field="url" label="轮播图图片">
                    <Upload tip="上传轮播图" :width="300" :height="150" v-model="productAdvert.url"></Upload>
                </a-form-item>
                <a-form-item field="skipGoodId" label="关联商品">
                    <a-select v-model="productAdvert.skipGoodId" allow-search allow-clear placeholder="请选择关联商品">
                        <a-option v-for="product in productList" :key="product.goodsId"
                            :value="product.goodsId.toString()" :label="product.goodsName">
                            <div style="display: flex; align-items: center;">
                                <a-avatar size="small" style="margin-right: 8px;"
                                    :image-url="'http://image.fuyj.com.cn/' + product.goodsThumb + '?imageslim/zlevel/7'" />
                                <span>{{ product.goodsName }}</span>
                            </div>
                        </a-option>
                    </a-select>
                </a-form-item>
                <a-form-item field="sortId" label="排序">
                    <a-input-number v-model="productAdvert.sortId" placeholder="请输入排序值" :min="1" />
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<style>
.advert-sort {
    font-size: 13px;
    color: #333;
    font-weight: 600;
}
</style>